﻿
Imports CaptchaDLL
Imports MeoTom.Core
Imports MeoTom.Core.BLL

Partial Public Class Article
    Inherits UI.Page

    Private ReadOnly _objArticle As New Articles()
    Private ReadOnly _util As New Utilities.Common()

    Public year As String = ""
    Public month As String = ""
    Public day As String = ""
    Public PageTitleRewrite As String = ""
    Public PageTitle As String = ""
    Public PageAbstract As String = ""
    Public PageUrl As String = ""
    Public SArticleId As String = ""

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        _util.SetSession("CaptchaImageText", CaptchaImage.GenerateRandomCode(CaptchaType.AlphaNumeric, 4))
        GetArticle()
    End Sub

    Public Sub WriteCat(ByVal catId As Integer, ByVal subCat As Integer)
        If subCat = 0 Then
            subCat = catId
        End If

        Dim strOut As New StringBuilder
        strOut.Append("<ul>")
        strOut.Append("     <li class=""first""><a href=""/"">Trang chủ</a></li>")
        Using dc As New MeoTomDataContext
            Dim categorySource = From c In dc.ArticleCategories Where c.CatID = catId Or c.CatID = subCat And c.SiteID = Configs.SiteID Order By c.SubCat Ascending Select c.CatID, c.Title, c.TitleNone, c.SubCat
            For Each CatItem In categorySource
                strOut.Append("<li><a href=""/c").Append(CatItem.CatID).Append("s").Append(CatItem.SubCat).Append("/").Append(CatItem.TitleNone).Append(""">").Append(Server.HtmlEncode(CatItem.Title)).Append("</a></li>")
            Next
        End Using
        strOut.Append("</ul>")
        nav2.InnerHtml = strOut.ToString
    End Sub

    Public Sub GetArticle()
        Try
            Dim iArticleId As Integer
            SArticleID = Request.QueryString("ArticleID").Replace(".aspx", "").Replace(".php", "").Replace(".htm", "").Replace(".asp", "")
            year = Request.QueryString("Year")
            month = Request.QueryString("Month")
            day = Request.QueryString("Day")
            PageTitleRewrite = Request.QueryString("Title")
            PageUrl = year & "/" & month & "/" & day & "/" & PageTitleRewrite & "-" & SArticleID

            Dim regex As New Regex("^[A-Fa-f0-9]*$")
            If Not regex.IsMatch(SArticleID) Then
                Response.Redirect("/Error.htm", False)
            End If

            iArticleId = _util.IntValue(SArticleID).ToString()

            'write article comment
            CommentContent.InnerHtml = WriteComment(iArticleId)

            'get content article from xml
            _objArticle.ReadXmlbyId(iArticleId, day, month, year)

            If Not "/" & PageUrl = _objArticle.ArticlePath Then
                Response.Redirect("/Error?e=404", False)
            Else
                If _objArticle.Approved Then
                    If Not _objArticle.ReleaseDate > DateTime.Now Then
                        If _objArticle.PostVisible = "1" Then
                            If _util.GetCookie("UserName") <> vbNullString Or _util.GetSession("UserName") <> vbNullString Then
                                LoadArticle()
                            Else
                                If _objArticle.ArticlePassword = vbNullString Then
                                    LoadArticle()
                                Else
                                    If _util.GetCookie("Pwd_" & _objArticle.ArticlesId.ToString()) = _objArticle.ArticlePassword Then
                                        LoadArticle()
                                    Else
                                        ArticleContent.Visible = False
                                        'ArticlePassword.Visible = True
                                        CommentContent.Visible = False
                                        CommentForm.Visible = False
                                        Page.Title = "MeoTom's Blog: Enter Password."
                                    End If
                                End If
                            End If
                        ElseIf _objArticle.PostVisible = "2" Then
                            If _util.GetCookie("UserName") <> vbNullString Or _util.GetSession("UserName") <> vbNullString Then
                                LoadArticle()
                            Else
                                Response.Redirect("/Error?e=404", False)
                            End If
                        Else
                            LoadArticle()
                        End If
                    Else
                        Response.Redirect("/Error?e=404", False)
                    End If
                Else
                    Response.Redirect("/Error?e=404", False)
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Public Sub LoadArticle()
        Try
            Dim strMedia As String = ""
            Const strVideo As String = "&nbsp;<img src=""/images/hasVideo.gif"" style=""padding:0 0px 5px 0;float:none;"" width=""15"" height=""9"" alt=""Video"" />"
            Const strImage As String = "&nbsp;<img src=""/images/HasImage.gif"" style=""padding:0 0px 5px 0;float:none;"" width=""10"" height=""10"" alt=""Images"" />"

            If _objArticle.IsMedia Then
                strMedia &= strVideo
            End If

            If _objArticle.IsPicture Then
                strMedia &= strImage
            End If

            If Not _objArticle.CommentEnabled Then
                CommentForm.Visible = False
            Else
                ltrAbstract.Text &= "<script language='javascript' type='text/javascript'>Util.writeEmoticons('divEmoticons');</script>"
            End If

            PageTitle = _objArticle.Title.ToString
            PageAbstract = Left(_util.NoHTML(Server.HtmlDecode(Server.HtmlDecode(_objArticle.Body.ToString.Replace(Environment.NewLine, " ")))), 200)

            lnkTitle.Text = _objArticle.Title.ToString & strMedia
            lnkTitle.NavigateUrl = "/" & PageUrl
            ltrAbstract.Text &= Server.HtmlDecode(_objArticle.Body.ToString)

            Dim str() As String = _objArticle.ArrayCatID.Split(New Char() {"|"c})
            WriteCat(str(0), str(1))

            ltrAbstract.Text &= "<script language='javascript' type='text/javascript'>"
            ltrAbstract.Text &= "   window.onload = function() {"
            ltrAbstract.Text &= "       MenuV2.selectedById(" & str(0) & "," & str(1) & ");"
            ltrAbstract.Text &= "       Util.sociable('" & Configs.HomeUrl & PageUrl & "', '" & PageTitle.Replace(" ", "+").Replace("'", "") & "', '" & Left(Replace(PageAbstract.Replace(" ", "+"), "++", ""), 50).Replace("'", "") & "', 'sociable');"
            If _objArticle.IsVote Then
                ArticleVote.Visible = True
                'ArticleVote.InnerHtml = "<div id=""VoteDetail""></div>"
                'ltrAbstract.Text &= "   Vote.writeVote(" + objArticle.ArticlesID.ToString() + ",""VoteDetail"");"
            End If
            ltrAbstract.Text &= "   }"
            ltrAbstract.Text &= "</script>"

            Page.Title = Server.HtmlDecode(PageTitle) & " - " & Configs.WebTitle
            Dim metaTag As New HtmlMeta()
            metaTag.Name = "description"
            metaTag.Content = Server.HtmlDecode(PageTitle) & " - " & PageAbstract
            Header.Controls.Add(metaTag)
        Catch ex As Exception

        End Try
    End Sub

    Public Function WriteComment(ByVal articleId As Integer) As String
        Dim totalComment As Integer = 1
        Dim strOut As New StringBuilder()
        Dim strComment As New StringBuilder()
        Using dc As New MeoTomDataContext
            'update count for article
            dc.Justin_Article_UpdateCount(articleID)
            'select comment
            Dim commentSource = From c In dc.Comments Where c.ArticleId = articleId And c.Status = 0 Order By c.CommentsID Ascending Select c.CommentsID, c.AddedBy, c.AddedByEmail, c.AddedByIP, c.AddedDate, c.Body, c.Status, c.AddedByURL, c.IsAdmin

            For Each CommentItem In commentSource
                If CommentItem.IsAdmin Then
                    strComment.Append("<li id=""Comments_").Append(totalComment).Append(""" class=""AdminComment"">")
                Else
                    strComment.Append("<li id=""Comments_").Append(totalComment).Append(""">")
                End If

                If CommentItem.AddedByURL = vbNullString Then
                    strComment.Append("<cite id=""Comments_User_").Append(totalComment).Append(""">").Append(CommentItem.AddedBy).Append(":</cite><br />")
                Else
                    strComment.Append("<cite id=""Comments_User_").Append(totalComment).Append("""><a href=""").Append(CommentItem.AddedByURL).Append(""" target=""blank"">").Append(CommentItem.AddedBy).Append(":</a></cite><br />")
                End If

                strComment.Append("<small class=""commentmetadata""><a href=""#Comments_").Append(totalComment).Append(""">").Append(String.Format("{0:dd/MM/yyyy}", CommentItem.AddedDate.Value.AddHours(Configs.TimeLine))).Append(" at ").Append(String.Format("{0:HH:mm tt}", CommentItem.AddedDate.Value.AddHours(Configs.TimeLine))).Append("</a></small>")
                strComment.Append("<p>").Append(CommentItem.Body).Append("</p><p><a href=""#PostComment"" onclick=""javascript:Util.InsertReplyUser(").Append(totalComment).Append(");"" class=""lnkReply"">[Reply]</a></p>")

                If CommentItem.IsAdmin Then
                    strComment.Append("<span class=""number NumberAdmin"">").Append(totalComment).Append("</span>")
                Else
                    strComment.Append("<span class=""number"">").Append(totalComment).Append("</span>")
                End If

                strComment.Append("</li>")
                totalComment = totalComment + 1
            Next
        End Using

        If Not strComment.Length = 0 Then
            strOut.Append("<h3><a href=""#Comments"" name=""Comments"" id=""Comments"" title=""Comments"">Comments (").Append(totalComment - 1).Append(")</a></h3><div class=""hr fl"">&nbsp;</div>")
            strOut.Append("<ol class=""CommentList"" id=""CommentList"">")
            strOut.Append(strComment.ToString)
            strOut.Append("</ol>")
        End If
        Return strOut.ToString
    End Function
End Class